package com.shop.front.util;


import javax.servlet.http.HttpServletRequest;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpUtil {

    public static String getIp(HttpServletRequest request) {
        // 反向代理时获取真实ip
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "localhost";
        }
        return ip;
    }



    public static String getIPv6(HttpServletRequest request) {
        // 先尝试从X-Forwarded-For获取，如果有多个IP则取第一个非localhost或空的地址
        String xffHeader = request.getHeader("X-Forwarded-For");
        if (xffHeader != null && !xffHeader.isEmpty()) {
            String[] forwardedIps = xffHeader.split(",");
            for (String ip : forwardedIps) {
                ip = ip.trim();
                if (!ip.equals("") && !"unknown".equalsIgnoreCase(ip)) { // 非空且非未知标识
                    if (isValidIPv6(ip)) {
                        return ip; // 如果是合法的IPv6地址，则返回
                    }
                }
            }
        }

        // 如果X-Forwarded-For不可靠或者没有设置，尝试其他头部
        String realIpHeader = request.getHeader("X-Real-IP");
        if (realIpHeader != null && isValidIPv6(realIpHeader)) {
            return realIpHeader;
        }

        // 最后，如果所有头部都无法得到IPv6地址，则使用getRemoteAddr()
        String remoteAddr = request.getRemoteAddr();
        if (isValidIPv6(remoteAddr)) {
            return remoteAddr;
        }

        // 如果以上方式均未获取到IPv6地址，则返回默认值或者其他处理
        return "Unknown";
    }




    // 检查是否为合法的IPv6地址
    private static boolean isValidIPv6(String ipAddress) {
        try {
            java.net.Inet6Address.getByName(ipAddress);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public static void main(String[] args) {
        try {
            byte[] ipv4Bytes = {12, 3, 2, 1};
            InetAddress ipv4Address = InetAddress.getByAddress(ipv4Bytes);
            Inet6Address ipv6Address = Inet6Address.getByAddress(null, ipv4Address.getAddress(), -1);
            System.out.println("IPv6地址: " + ipv6Address.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }


}
